//
//  DownLoad.m
//  Slice
//
//  Created by lanou on 16/6/23.
//  Copyright © 2016年 wangjinchao. All rights reserved.
//

#import "DownLoad.h"
@implementation DownLoad

//下载类的封装
- (instancetype)initWithURL:(NSString *)URLString saveNameL:(NSString *)saveFileName {
     self = [super init];
    if ( self) {
        _urlString = URLString;
        
        NSArray *arr = [_urlString componentsSeparatedByString:@"."];
        
        _saveFileName = [saveFileName stringByAppendingString:[NSString stringWithFormat:@".%@",arr.lastObject]];
        
//        下载所需的url对象
        NSURL *url = [NSURL URLWithString:_urlString];
//        下载使用的 NSURLSession 
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        
        _downLoadTask = [session downloadTaskWithURL:url];
        
        
    }
    return self;
}



//下载开始的方法
- (void)beginLoad {
    self.isLoading = YES;
    [self.downLoadTask resume];
}

//取消下载
- (void)cancel {
    self.isLoading = NO;
    [self.downLoadTask cancel];
}

//暂停下载
- (void)pause {
    self.isLoading = NO;
    [self.downLoadTask suspend];
}

#pragma mark -------下载的协议方法-------
//下载完成
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
//    location 是文件下载完成所在的地址 默认在 temp 文件夹下面 我们需要移动到其他的地方 否则会被系统删除
    NSLog(@"下载完成");
    BOOL result = [[NSFileManager defaultManager] fileExistsAtPath:locaFolderPath];
    if (!result) {
        [[NSFileManager defaultManager] createDirectoryAtPath:locaFolderPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
//    目标路径
    NSString *str = [locaFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", _saveFileName]];
    
//    将文件移动到指定的位置
    [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:str error:nil];
    
    [[DownLoadMaqnager shareInstace].URLArray removeObject:_urlString];
    [[DownLoadMaqnager shareInstace].taskArray removeObject:self];
//    发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:downLoadFinishNotification object:self];
    NSLog(@"%@",str);
}
//正在下载中
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
    
}
//正在写入中
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)sWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
//    didWriteData 获得本次数据的大小
//    totalBytesWritten 已经写入的总大小
//    totalBytesExpectedToWrite 这个文件的总大小
    
//    self.proportion = totalBytesWritten / (float)totalBytesExpectedToWrite;
    if (self.sendValue) {
        self.sendValue(totalBytesWritten, totalBytesExpectedToWrite);

    }
    
}




@end

@implementation DownLoadMaqnager

//单例
+ (instancetype)shareInstace {
    static DownLoadMaqnager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[DownLoadMaqnager alloc] init];
        manager.URLArray = [[NSMutableArray alloc] initWithCapacity:0];
        manager.taskArray = [NSMutableArray array];
    });
    return manager;
}


//添加一个下载任务保存文件名称 添加结果
- (DownLoad *)addDownLoadWithURL:(NSString *)urlString saveFileName:(NSString *)saveFileName addResult:(void(^)(addResult addResult))resultCallBack {
//拼接后缀名
    NSArray *arr = [urlString componentsSeparatedByString:@"."];
    NSString *saveName = [saveFileName stringByAppendingFormat:@".%@",arr.lastObject];
    
    
//    判断这个是否添加过
    if ([self.URLArray containsObject:urlString]) {
        resultCallBack(addResultDownLoading);
        return nil;
    } else if ([[self areadyDownLoad] containsObject:saveName]) {
//     判断文件是否已经下载完成
        resultCallBack(addResultLoadFinish);
       
        return nil;
    } else {
        DownLoad *download = [[DownLoad alloc] initWithURL:urlString saveNameL:saveFileName];
        resultCallBack(addResultSuccess);
//        将网址加入到数组中
        [self.URLArray addObject:urlString];
        [self.taskArray addObject:download];
        return download;
    }
}


- (NSArray *) areadyDownLoad {
//    此方法返回文件下所有的文件名
    return [[NSFileManager defaultManager] contentsOfDirectoryAtPath:locaFolderPath error:nil];
}

@end










